<?php
namespace Common\Library;

/**
 * Description of http://www.baishuku.com/
 *
 * @author gangguo
 */
class baishuku{

    protected $BookArticle;
    protected $detailUrl;
    protected $id;
    protected $book_id;
    protected $author_id;
    protected $authorName;
    protected $bookName;

    public function __construct($id,$url = ''){
        header("Content-Type:text/html;charset=utf-8;");
        $this->id = $id;
        if(empty($url)){
            $this->updateList();
        }else{
            $this->detailUrl = $url;
            $this->addNewBook();
        }
        exit('over good');
    }

    //添加一本新书x
    protected function addNewBook(){
        if(empty($this->detailUrl)){
            exit('空URL地址');
        }
        set_time_limit(0);
        $pathFile = './Runtime/Collect/baishuku/addbook.html';
        \Common\Library\COM\CollectDo::downPage($this->detailUrl,$pathFile);
        $getStr = \Common\Library\COM\CollectDo::getHtml($pathFile);
        $bookInfo = \Common\Library\COM\CollectDo::getSubstr($getStr,'<td width="80%" align="center" valign="middle"','<td align="center" class="title">[最新书评');
        unset($getStr,$pathFile);

        //提取作者
        $this->authorName = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'作&nbsp;&nbsp;&nbsp; 者：','<td width="25%">管 理 员',FALSE);
        $this->authorName = trim(strip_tags($this->authorName));
        if(empty($this->authorName)){
            p($bookInfo);
            $this->writeLog('作者为空:'.$this->authorName.' @@ '.$this->detailUrl,'ERR');
        }

        $this->author_id = D('Common/BookAuthor')->getAuthorId($this->authorName);
        //提取书籍名称
        $this->bookName = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'<span style="font-size:16px; font-weight: bold; line-height: 150%">','</span></td>',FALSE);
        if(empty($this->bookName)){
            $this->writeLog('书名为空!:'.$this->detailUrl.'@@'.var_export($bookInfo,1),'ERR');
        }

        $Book = new \Common\Model\BookModel();
        $unique = md5($this->bookName.$this->author_id);
        //书本重复检测
        $this->book_id = $Book->checkBookRepeart($unique);
        //p($this->book_id);exit;
        if(empty($this->book_id)){//新书入库
            //提取简介
            $intro = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'内容简介：</span><br />','<br /><br />',FALSE);
            $replace = array('&amp;nbsp','&nbsp;','()','&lt;/p&gt;');
            $intro = str_replace($replace,'', $intro);
            //提取分类
            $cate = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'类&nbsp;&nbsp;&nbsp; 别：','<td width="25%">作&nbsp;&nbsp;&nbsp; 者：',FALSE);
            $cate = strip_tags($cate);
            $cate = \Common\Library\COM\CollectDo::changeCateName($cate);
            if(empty($cate)){
                $this->writeLog('入库错误,没有分类:'.var_export($cate,1).'@@'.var_export($bookInfo,1),'ERR');
            }

            $image = \Common\Library\COM\CollectDo::doImagePath();;
            //分类处理
            $cate_id = D('Common/BookCate')->getCateId($cate);
            //书籍状态
            $status = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'文章状态：','<td>首发状态',FALSE);
            $status = strip_tags($status);
            if($status == '连载中'){
                $status = 'ing';
            }else{
                $status = 'end';
            }
            $dataBook = array(
                'book_name'=>$this->bookName,
                'author_id'=>$this->author_id,
                'status'=>$status,
                'cate_id'=>$cate_id,
                'introduction'=> htmlentities($intro,ENT_COMPAT,'UTF-8'),
                'img'=>$image,
                'create_time'=>  time(),
                'year'=> date('Y'),
                'month'=>  date('m'),
                'day'=>  date('d'),
                'unique'=>$unique
            );
            //p($dataBook);exit;
            if($this->book_id = $Book->saveBook($dataBook)){
                $img = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'<img src="','" border="0" width="100" height="125"',FALSE);
                \Common\Library\COM\CollectDo::downPage($img, '.'.$image);
            }
        }
        //新书开始入库
        if(empty($this->book_id)){
            $this->writeLog('入库错误,书本未入库:'.var_export($dataBook,1).'@@'.var_export($Book->getDbError(),1),'ERR');
        }else{
            $this->writeLog('bookinstall.新书开始入库:'.var_export($this->bookName,1));
            $listUrl = \Common\Library\COM\CollectDo::getSubstr($bookInfo,'<td align="center"><a href="','"><font style="color:red;">阅读本书');
            $this->articleCollection($listUrl);
        }
        unset($Book,$bookInfo);
    }

    //章节列表名称入库
    protected function articleCollection($listUrl = ''){
        $pathFile = './Runtime/Collect/baishuku/booklist.html';
        \Common\Library\COM\CollectDo::downPage($listUrl,$pathFile);
        $getStr = \Common\Library\COM\CollectDo::getHtml($pathFile);
        $listInfo = \Common\Library\COM\CollectDo::getSubstr($getStr,'<table ','</table>');
        unset($getStr,$pathFile);
        if(empty($listInfo) || empty($this->book_id)){ return FALSE;}
        //章节名称和篇名入库
        $count = mb_substr_count($listInfo,'<td class="ccss">');
        $this->BookArticle = new \Common\Model\BookArticleModel();
        for($i=0;$i<$count;$i++){
            $nowInfo = \Common\Library\COM\CollectDo::getSubstr($listInfo,'','</td>',FALSE);
            if(strpos($nowInfo, '<a href="') <= 0){
                $listInfo =  \Common\Library\COM\CollectDo::getSubstr($listInfo,'</td>','',FALSE);
                continue;
            }
            //获取章节名称
            $article_name = \Common\Library\COM\CollectDo::getSubstr($nowInfo,'title="','</a>',FALSE);
            $article_name = \Common\Library\COM\CollectDo::getSubstr($article_name,'">','',FALSE);
            if(empty($article_name)){
                $this->writeLog('章节名称不能为空!@Value:'.var_export($nowInfo,1).'@URL:'.$this->detailUrl,'ERR');
            }
            $this->writeLog($article_name.':章节入库开始!');
            $unique = md5($this->book_id.$article_name);
            $result = $this->BookArticle->checkArtcileRepeat($unique);
            if($result){//重复章节检测
                $this->writeLog($article_name.' ====> 重复章节');
            }else{//采集新章节
                $article_num = \Common\Library\COM\CollectDo::getArticleNum($article_name);
                $articleDate = array(
                    'book_id'=> $this->book_id,
                    'article_name'=> $article_name,
                    'create_time'=>  time(),
                    'year'=>  date('Y'),
                    'month'=>  date('m'),
                    'day'=>  date('d'),
                    'article_num'=> $article_num,
                    'update_time' => time(),
                    'unique'=>$unique,
                    'content'=>$contentPath
                );
                $article_id = $this->BookArticle->add($articleDate);
                if(empty($article_id)){
                    $this->writeLog('章节存储失败!@'.var_export($articleDate,1).var_export($this->BookArticle->getDbError(),1),'ERR');
                }else{
                    //获取章节内容url地址
                    $article_url = \Common\Library\COM\CollectDo::getSubstr($nowInfo,'<a href="','" title="',FALSE);
                    //获取章节内容并存储
                    $contentPath = $this->contentCollection($listUrl.$article_url);
                }
            }
            $listInfo =  \Common\Library\COM\CollectDo::getSubstr($listInfo,'</td>','',FALSE);
        }
        $this->writeLog($this->detailUrl.'本书入库完成!');
        return FALSE;
    }

    //章节内容入库
    protected function contentCollection($contentUrl = ''){
        if(empty($contentUrl)){
            $this->writeLog('内容章节URL地址空:'.var_export($contentUrl,1),'ERR');
            exit;
        }
        $savePath = './Runtime/Collect/baishuku/content.html';
        \Common\Library\COM\CollectDo::downPage($contentUrl, $savePath);
        $contentA = \Common\Library\COM\CollectDo::getHtml($savePath,'','utf-8');
        if(empty($contentA)){
            \Common\Library\COM\CollectDo::downPage($contentUrl, $savePath);
            //sleep(3);
            $contentA = \Common\Library\COM\CollectDo::getHtml($savePath);
        }
        $contentA = \Common\Library\COM\CollectDo::getSubstr($contentA,')</a></div>','<div align="center"><scrip',FALSE);

        $replace = array(
                '</div>','<a href="','<a href=','<a','</a>',
                'www.baishuku.com','baishuku.com','百书库');
        $contentT = str_replace($replace,'', $contentA);unset($contentA);

        if(!\Common\Library\COM\CollectDo::checkSpecialStr($contentT)){
            $data = array('id'=>$this->id,'dotime'=>time(),'disabled'=>4,'remark'=>'采集章节内容有误,包含特殊字符:'.$contentUrl);
            \HelloAdmin\Model\CrontabModel::updateData($data);
            $this->writeLog('采集章节内容有误,包含特殊字符:'.var_export($contentUrl,1).'@@'.var_export($contentT,1),'ERR');
        }
        $contentT = htmlentities($contentT,ENT_COMPAT,'UTF-8');
        $contentPath = \Common\Library\COM\CollectDo::doContentPath();
        $handel = fopen('.'.$contentPath,'x+');
        if($handel && fwrite($handel,$contentT) !== FALSE){
            fclose($handel);
            return $contentPath;
        }
        $this->writeLog('章节内容'.var_export($contentT,1));
        $this->writeLog('章节内容存储失败!@'.var_export($contentPath,1).'|@|'.var_export($contentUrl,1),'ERR');
    }

    //采集日志记录
    private function writeLog($message,$level='INFO'){
        \Think\Log::write($message,$level,$type='','./Runtime/Collect/baishuku/logs-'.  date('Ymd').'.log');
        if($level == 'ERR'){
            exit($message);
        }
    }




    public function updateList(){
        set_time_limit(0);
        $updateUrl = 'http://baishuku.com/booksinfotoplastupdate/0/1.htm';
        $pathFile = './Runtime/Collect/baishuku/booklist.html';
        \Common\Library\COM\CollectDo::downPage($updateUrl, $pathFile);
        $getStr = \Common\Library\COM\CollectDo::getHtml($pathFile);
        $booklist = \Common\Library\COM\CollectDo::getSubstr($getStr,'</tr>','</table>',FALSE);
        unset($getStr,$pathFile);
        //获取书籍名称
        $count = mb_substr_count($booklist,'</tr>');
        $Book = new \Common\Model\BookModel();
        $Author = new \Common\Model\BookAuthorModel();
        for($i=0;$i<$count;$i++){
            $now = \Common\Library\COM\CollectDo::getSubstr($booklist,'','</tr>',FALSE);
            $bookName = \Common\Library\COM\CollectDo::getSubstr($now,'.htm">','</a></td>');
            $authorName = \Common\Library\COM\CollectDo::getSubstr($now,'<td class="even"><a href="','',FALSE);
            $authorName = \Common\Library\COM\CollectDo::getSubstr($authorName,'<td class="odd">','<td class="even">');
            $authorName = trim(strip_tags($authorName));
            //p($now);p($authorName);p($bookName);exit;
            if(empty($bookName) || empty($authorName)){
                $this->writeLog('书名,作者,或为空!:'.var_export($now,1).'@@'.var_export($updatelist,1),'ERR');
            }
            $author_id = $Author->getAuthorId($authorName);
            $unique = md5($bookName.$author_id);
            //书本重复检测
            $this->book_id = $Book->checkBookRepeart($unique);
            if($this->book_id > 0){//更新已有的书籍
                $articleName = \Common\Library\COM\CollectDo::getSubstr($now,'target="_blank">','',FALSE);
                $articleName = \Common\Library\COM\CollectDo::getSubstr($articleName,'','</a></td>');

                if(empty($articleName)){
                    $this->writeLog($offset.':====> 章节名称空'.var_export($now,1),'ERR');
                }
                $unique = md5($this->book_id.$articleName);
                $this->BookArticle = new \Common\Model\BookArticleModel();
                $result = $this->BookArticle->checkArtcileRepeat($unique);

                if($result){//重复章节检测
                    $this->writeLog($articleName.' ====> 重复章节');
                }else{
                    //获取章节内容地址
                    $articleListUrl = \Common\Library\COM\CollectDo::getSubstr($now,'<td class="even"><a href="','" target="_blank">');
                    $this->articleCollection($articleListUrl);
                }
            }
            $booklist = \Common\Library\COM\CollectDo::getSubstr($booklist,'</tr>','',FALSE);
            $this->writeLog($bookName.'||====> 新书跳过，更新下一个章节 ====>');
            continue;
        }
    }

}
